package com.hoodbrains.insideloc.locator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.hoodbrains.insideloc.R;
import com.hoodbrains.insideloc.guidedshopping.ShowMapActivity;
import com.hoodbrains.insideloc.maps.CreateMapActivity;
import com.hoodbrains.insideloc.utils.Catalog;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ShopListActivity extends ListActivity 
	implements RelevantLocationListener,
	OnItemClickListener {
	Context mContext;
	List<SuperMarketPOI> shops;
	// States
	private boolean firstLocDone = false;
	// End states.
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContext = this;
		
		getListView().setBackgroundResource(R.drawable.background);
		getListView().setCacheColorHint(0x00000000);
		
		shops = Catalog.getInstance().getShops();
			
		setListAdapter(new ArrayAdapter<String>(this, R.layout.shop_choice, new ArrayList<String>()));
		
		final ListView lv = getListView();
		lv.setTextFilterEnabled(true);
		
		lv.setOnItemClickListener(this);
		
		Locator.getInstance().subscribeForRelevantUpdates(this);
	}
	
	public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		 SuperMarketPOI smPOI = (SuperMarketPOI)getListAdapter().getItem(position) ;
		 Catalog cata = Catalog.getInstance();
		 
		 cata.setCurrentSuperMarketID(smPOI.getOsmId());
		 
		 Intent intent;
		 if (cata.mapExists(smPOI.getOsmId())) {
			 intent = new Intent(this, ShowMapActivity.class);
		 } else {
			 cata.copyEmptySM(smPOI.getOsmId());
			 //todo.
			 intent = new Intent(this, CreateMapActivity.class);
		 }
//		 i.putExtra("osm_id", smPOI.getOsmId());
//			startActivityForResult(i, SPLASH_AD_ACTIVITY_CODE);
			startActivity(intent);
		      // When clicked, show a toast with the TextView text
		     
		
	}
	
		
	public void onLocationUpdate(Location loc, boolean locationChanged) {
		if (!firstLocDone) {
			firstLocDone = true;

			// Hide waiting for location dialog.
//			if (waitingLocationDialog != null) {
//				waitingLocationDialog.dismiss();
//				waitingLocationDialog = null;
//			}
			
			//sort the shop list 
			for(SuperMarketPOI shop:shops){
				shop.computeDistance(loc);
			}
			Collections.sort(shops, new ShopComparator());
			
			setListAdapter(new ArrayAdapter<SuperMarketPOI>(this, R.layout.shop_choice, shops));
		}
	}
}
